//
//  IslanDetailedLocalCtrl.m
//  diaoyuren
//
//  Created by 钓鱼人 on 16/4/13.
//  Copyright © 2016年 game. All rights reserved.
//

#import "IslanDetailedLocalCtrl.h"
#import "CustomPointAnnotation.h"
#import "CalloutMapAnnotation.h"
#import "CallOutAnnotationView.h"
#import "InformView.h"
#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相关所有的头文件
//
#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地图功能所有的头文件

#import <BaiduMapAPI_Search/BMKSearchComponent.h>//引入检索功能所有的头文件

#import <BaiduMapAPI_Cloud/BMKCloudSearchComponent.h>//引入云检索功能所有的头文件
#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件

#import <MapKit/MapKit.h>

@interface IslanDetailedLocalCtrl ()<BMKMapViewDelegate, BMKGeoCodeSearchDelegate,UIActionSheetDelegate,BMKLocationServiceDelegate>
{

    BMKGeoCodeSearch* _geocodesearch;
    
    bool isGeoSearch;
    
    CalloutMapAnnotation *_calloutMapAnnotation;
    
    CGFloat _latitude;//经度
    
    CGFloat _longitute;//纬度
    
    BMKLocationService* _locService;

}

@property (nonatomic,strong) BMKMapView *mapView;

@property (nonatomic,strong) NSMutableArray *availableMaps;
@end

@implementation IslanDetailedLocalCtrl

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.app.myTabBar.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden = YES;
    
    [_mapView viewWillAppear];
    _mapView.delegate = self;
    _geocodesearch.delegate = self;
    _locService.delegate = self;
}

-(NSMutableArray *)availableMaps{
    if (!_availableMaps) {
        _availableMaps = [NSMutableArray array];
    }
    return _availableMaps;
}
- (IBAction)backAction:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    BMKMapView* mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    [self.view addSubview:mapView];
    
    _mapView = mapView;
    
    [_mapView setMapType:BMKMapTypeStandard];//设置地图类型
    _geocodesearch = [[BMKGeoCodeSearch alloc]init];
    [_mapView setZoomLevel:12];
    
    _locService = [[BMKLocationService alloc]init];
    
    
    /**
     *  根据具体地址显示进行地理编码
     */
    isGeoSearch = true;
    BMKGeoCodeSearchOption *geocodeSearchOption = [[BMKGeoCodeSearchOption alloc]init];
        geocodeSearchOption.city= [self.Myud valueForKey:@"localName"];
        geocodeSearchOption.address = _localString;

     [_geocodesearch geoCode:geocodeSearchOption];

    
        [_locService startUserLocationService];//开启定位服务
    
        _mapView.showsUserLocation = NO;//先关闭显示的定位图层
        _mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
        _mapView.showsUserLocation = YES;//显示定位图层
}

/**
 *用户方向更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
//    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
//    
//    NSLog(@"%@--%@",userLocation.title,userLocation.subtitle);
    [_mapView updateLocationData:userLocation];
}

/**
 *在地图View停止定位后，会调用此函数
 *@param mapView 地图View
 */
- (void)didStopLocatingUser
{
//    NSLog(@"stop locate");
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
//    NSLog(@"location error");
}

/**
 *  显示具体位置调用代理方法
 *
 */
-(void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == 0) {
        //        //大头针
        CustomPointAnnotation* item = [[CustomPointAnnotation alloc]init];
        item.coordinate = result.location;
        
        item.title = self.name;
        item.subtitle = self.localString;
        
        [_mapView addAnnotation:item];
        _mapView.centerCoordinate = result.location;
        _latitude = item.coordinate.latitude;
        _longitute = item.coordinate.longitude;
        
    }
}

/**
 *  改变大头针图片
 */
-(BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation{
    
    static NSString *annotationIdentifier = @"customAnnotation";
    
    if ([annotation isKindOfClass:[CustomPointAnnotation class]]) {
        
        BMKPinAnnotationView *annotationview = [[BMKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:annotationIdentifier];
        
        if (self.chargeType.intValue==1) {
            annotationview.image = [UIImage imageNamed:@"free_point~iphone"];
        }else{
            annotationview.image = [UIImage imageNamed:@"charge_point~iphone"];
        }
        
        [annotationview setAnimatesDrop:YES];
        annotationview.canShowCallout = NO;//关闭自带的吹出框
        
        [self mapView:mapView didSelectAnnotationView:annotationview];
        return annotationview;
        
    }else if ([annotation isKindOfClass:[CalloutMapAnnotation class]]){
        
        
        //如果可以重用
        CallOutAnnotationView *callout = (CallOutAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"calloutview"];
        
        //否则创建新的calloutView
        if (!callout) {
            callout = [[CallOutAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"calloutview"];
        }
        
        //开始设置添加marker时的赋值
        callout.contentView.localName.text = self.name;
        callout.contentView.localDesc.text =self.localString;
        [callout.contentView.gotoBtn addTarget:self action:@selector(GotoClick) forControlEvents:UIControlEventTouchUpInside];
        return callout;
    }
    return nil;
}


-(void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view{
    
    //CustomPointAnnotation 是自定义的marker标注点，通过这个来得到添加marker时设置的pointCalloutInfo属性
    CustomPointAnnotation *annn = (CustomPointAnnotation*)view.annotation;
    
    if ([view.annotation isKindOfClass:[CustomPointAnnotation class]]) {
        
        //如果点到了这个marker点，什么也不做
        if (_calloutMapAnnotation.coordinate.latitude == view.annotation.coordinate.latitude&&
            _calloutMapAnnotation.coordinate.longitude == view.annotation.coordinate.longitude) {
            
            return;
        }
        
        //如果当前显示着calloutview，又触发了select方法，删除这个calloutview annotation
        if (_calloutMapAnnotation) {
            [mapView removeAnnotation:_calloutMapAnnotation];
            _calloutMapAnnotation=nil;
            
        }
        
        //创建搭载自定义calloutview的annotation
        _calloutMapAnnotation = [[CalloutMapAnnotation alloc] initWithLatitude:view.annotation.coordinate.latitude andLongitude:view.annotation.coordinate.longitude];
        
        //把通过marker(ZNBCPointAnnotation)设置的pointCalloutInfo信息赋值给CalloutMapAnnotation
        _calloutMapAnnotation.locationInfo = annn.pointCalloutInfo;
        
        [mapView addAnnotation:_calloutMapAnnotation];
        
        [mapView setCenterCoordinate:view.annotation.coordinate animated:YES];
    }
}

/**
 *  点击导航
 */
-(void)GotoClick{
    
    [self availableMapsApps];
    
    UIActionSheet *action = [[UIActionSheet alloc] init];
    
    [action addButtonWithTitle:@"使用系统自带地图导航"];
    for (NSDictionary *dic in self.availableMaps) {
        [action addButtonWithTitle:[NSString stringWithFormat:@"使用%@导航", dic[@"name"]]];
    }
    [action addButtonWithTitle:@"取消"];
    action.cancelButtonIndex = self.availableMaps.count + 1;
    action.delegate = self;
    [action showInView:self.view];
}
//检测用户手机可用的导航软件
- (void)availableMapsApps {
    [self.availableMaps removeAllObjects];
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://map/"]]){
        
        NSDictionary *dic = @{@"name": @"百度地图",};
        [self.availableMaps addObject:dic];
    }
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
        
        NSDictionary *dic = @{@"name": @"高德地图"};
        [self.availableMaps addObject:dic];
    }
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"comgooglemaps://"]]) {
        NSDictionary *dic = @{@"name": @"Google Maps"};
        [self.availableMaps addObject:dic];
    }
}
//用户选择导航软件
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    NSString *btnTitle = [actionSheet buttonTitleAtIndex:buttonIndex];
    //终点
    CLLocationCoordinate2D endLocal = CLLocationCoordinate2DMake(_latitude, _longitute);
    
    if (buttonIndex==0) {//打开苹果自带地图
        
        MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
        MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:endLocal addressDictionary:nil]];
        [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
                       launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,
                                       MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
    }
    
    
    if ([btnTitle rangeOfString:@"百度地图"].length!=0) {
        
        
        NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=目的地&mode=driving&coord_type=gcj02",endLocal.latitude, endLocal.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
    }
    
    if ([btnTitle rangeOfString:@"高德地图"].length!=0) {
        NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=%@&lat=%f&lon=%f&dev=0&style=2",@"diaoyur",@"diaoyurMap",endLocal.latitude, endLocal.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
    }
    
    if ([btnTitle rangeOfString:@"Google Maps"].length!=0) {
        
        NSString *urlString = [[NSString stringWithFormat:@"comgooglemaps://?x-source=%@&x-success=%@&saddr=&daddr=%f,%f&directionsmode=driving",@"diaoyur",@"diaoyurMap",endLocal.latitude, endLocal.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
    }
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [_mapView viewWillDisappear];
    
    _mapView.delegate = nil; // 不用时，置nil
    _geocodesearch.delegate = nil;
    
    _locService.delegate = nil;
}

- (void)dealloc {
//    if (_geocodesearch != nil) {
        _geocodesearch = nil;
//    }
    
//    if (_mapView) {
        _mapView = nil;
//    }
    _locService = nil;
}

@end